package cool.houge.pig.infra.config;

import cool.houge.pig.infra.controller.RegisterController;
import cool.houge.pig.infra.controller.TokenController;
import cool.houge.pig.infra.controller.WeixinAuthController;
import cool.houge.pig.infra.controller.WeixinLoginController;
import cool.houge.pig.infra.web.LoginChannelInterceptor;
import cool.houge.pig.infra.web.WebErrorHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * WebFlux 路由配置.
 *
 * @author KK (kzou227@qq.com)
 */
@Configuration
public class RouterConfiguration {

  private final WebErrorHandler errorHandler;
  private final LoginChannelInterceptor loginChannelInterceptor;

  public RouterConfiguration(
      WebErrorHandler errorHandler, LoginChannelInterceptor loginChannelInterceptor) {
    this.errorHandler = errorHandler;
    this.loginChannelInterceptor = loginChannelInterceptor;
  }

  @Bean
  public RouterFunction<ServerResponse> basicRoutes(
      RegisterController register, TokenController token, WeixinAuthController weixinAuth) {
    return RouterFunctions.route()
        .POST("/registers/email", register::emailRegister)
        .GET("/registers/email/activate", register::activateEmail)
        // OAuth 认证接口
        .POST("/oauth/token", token::token)
        // 微信小程序认证
        .POST("/oauth/weixin/xcx.a", weixinAuth::xcxa)
        .onError(Exception.class, errorHandler::handle)
        .build();
  }

  @Bean
  public RouterFunction<ServerResponse> loginRoutes(WeixinLoginController weixinLogin) {
    return RouterFunctions.route()
        // 微信小程序登录
        .POST("/login/weixin-xcx", loginChannelInterceptor.handle(weixinLogin::xcx))
        .onError(Exception.class, errorHandler::handle)
        .build();
  }
}
